/**
* Created by GoLand.
* User: link1st
* Date: 2019-07-25
* Time: 09:59
 */

package main

import (
	"fmt"
	"io"
	"net/http"
	_ "net/http/pprof"
	"os"
	"os/exec"
	"time"

	"chat.com/model"
	"chat.com/pkg/cache"
	"chat.com/register"
	"chat.com/router"
	"chat.com/server/grpc/grpcserver"
	"chat.com/server/http/httphandler"
	"chat.com/server/task"
	"chat.com/server/wsserver"
	"chat.com/server/wsserver/connection"
	"chat.com/setting"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func main() {
	// 程序退出时删除grpc服务
	setting.Init()
	register.Init()
	defer register.ServerRegisterInstance.DelNode(
		setting.ZookeeperSetting.AccServerCenter,
		setting.AccServerSetting.Name,
	)

	//setting.Init()
	//initConfig()

	//initFile()

	model.Setup()
	cache.Init()
	httphandler.Init()
	//initRedis()

	r := gin.Default()
	// 初始化路由
	router.GinInit(r)
	router.WebSocketInit()

	// 定时任务
	task.Init()

	// 服务注册
	//task.ServerInit()
	//register.Init()

	go wsserver.StartWebSocket()
	// grpc
	go grpcserver.Init()

	go open()

	go pprofServer()

	go connection.CheckConnectionManagerInstance()

	accAddr := setting.AccServerSetting.Host
	// 注册聊天服务
	register.ServerRegisterInstance.RegisterNode(
		setting.ZookeeperSetting.AccServerCenter, setting.AccServerSetting.Name, setting.AccServerSetting.Host,
	)

	http.ListenAndServe(accAddr, r)
}

// 初始化日志
func initFile() {
	// Disable Console Color, you don't need console color when writing the logs to file.
	gin.DisableConsoleColor()

	// Logging to a file.
	logFile := viper.GetString("app.logFile")
	f, _ := os.Create(logFile)
	gin.DefaultWriter = io.MultiWriter(f)
}

func initConfig() {
	viper.SetConfigName("config")
	viper.AddConfigPath(".") // 添加搜索路径

	err := viper.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	fmt.Println("config app:", viper.Get("app"))
	fmt.Println("config redis:", viper.Get("redis"))

}

/*
func initRedis() {
	redislib.ExampleNewClient()
}*/

func open() {

	time.Sleep(1000 * time.Millisecond)

	httpUrl := viper.GetString("app.httpUrl")
	httpUrl = "http://" + httpUrl + "/home/index"

	fmt.Println("访问页面体验:", httpUrl)

	cmd := exec.Command("open", httpUrl)
	cmd.Output()
}

func pprofServer() {
	ip := "0.0.0.0:6060"
	if err := http.ListenAndServe(ip, nil); err != nil {
		fmt.Printf("start pprof failed on %s\n", ip)
	}
}
